#include "degfx/driver.h"

#ifdef MX__DRIVER_DJGPP

#   include <dpmi.h>
#   include <conio.h>

/* Mouse variables */
unsigned mx__djgpp_mouse_valid = false;
static int mx__djgpp_mouse_mx = 0;	/* internal position, in mickeys */
static int mx__djgpp_mouse_my = 0;

/* Quite a bit of the mouse code here has been taken from Allegro */
#   define MICKEY_TO_COORD_X(n)        ((n) / 2)
#   define MICKEY_TO_COORD_Y(n)        ((n) / 2)
#   define COORD_TO_MICKEY_X(n)        ((n) * 2)
#   define COORD_TO_MICKEY_Y(n)        ((n) * 2)

unsigned mx__djgpp_pointer(void)
{
	int x, y;
	__dpmi_regs regs;

	if (!mx__djgpp_mouse_valid)
		return false;

	/* Get mouse button data */
	regs.x.ax = 0x0003;
	__dpmi_int(0x33, &regs);
	mx__mouseb = regs.x.bx;

	/* Get mouse mickey data */
	regs.x.ax = 0x000b;
	__dpmi_int(0x33, &regs);

	x = (signed short) regs.x.cx;
	y = (signed short) regs.x.dx;

	/* Get the mouse coordinates */
	mx__mousex = MICKEY_TO_COORD_X(mx__djgpp_mouse_mx + x);
	mx__mousey = MICKEY_TO_COORD_Y(mx__djgpp_mouse_my + y);

	/* Limit the mouse coordinates to on screen */
	mx__mousex = MX_MID(mx__args.screen.x1, mx__mousex, mx__args.screen.x2);
	mx__mousey = MX_MID(mx__args.screen.y1, mx__mousey, mx__args.screen.y2);
	mx__djgpp_mouse_mx = COORD_TO_MICKEY_X(mx__mousex);
	mx__djgpp_mouse_my = COORD_TO_MICKEY_Y(mx__mousey);

	return true;
}

unsigned mx__djgpp_key(int *scan, int *ascii)
{
	if (!kbhit())
		return false;

	*scan = 0;
	*ascii = getch();

	if (*ascii == 0)
		*scan = getch();

	return true;
}

#endif
